import React, { useEffect, useState } from "react";
import { Space, Button, Modal, Toast, Avatar, Grid, AutoCenter,  } from "antd-mobile"
import {
  API,
  REDIRECT_COVER,
  REDIRECT_TITLE,
  REDIRECT_DESC,
  BASE_PATH,
} from "@/config";
import { useRouter } from "next/router";
import { appNavigate, appTypeCheck, checkENV, checkENV2, navigateTo } from "@/utils";
import requewt from "@/utils/requewt";
import callFeedback from "@/components/common/modalFeedback";
import { GiftComp, PrizeComp, RuleComp, StuffComp } from "@/components/common";
import GameResult from "@/components/common/modalFeedback/game.result";
import { usePathname } from "next/navigation";
import useShare from "../hooks/useShare";
import { useToolbar } from "./useToolbar";

const pageName = "toolbar";
const klassName = pageName.replace(/\./g, '-');

export default function Toolbar({user}) {
  const [visible, setVisible] = useState(undefined);
  const [loading, setLoading] = useState(undefined);
  const [env, setENV] = useState(undefined);
  const router = useRouter();
  const pathname = usePathname();
  const {handleAppShareToH5} = useShare()
  const { handleShowPrize } = useToolbar()
  let flag = 0;

  useEffect(() => {
    (async () => {
      waitForAuth()
      const seen = sessionStorage.getItem(`seen`);
      if (!seen) {
        compHandler.rule();
        sessionStorage.setItem(`seen`, `1`)
      }
    })()
  }, [])

  // useEffect(() => {
  //   if (env !== `mini`) return;
  //   // 处理小程序通讯的分享
  //   const data = {
  //     title: REDIRECT_TITLE, // 分享标题
  //     path: REDIRECT_WX_URL,
  //     imageUrl: REDIRECT_WX_COVER
  //   }
  //   wx.miniProgram.postMessage({data})
  // }, [env])

  /**
   * 等待环境加载
   * @param ev
   */
  const waitForAuth = (ev) => {
    if (flag >= 30) {
      // Toast.show({duration: 1000, content: `持续授权失败！请保证网络畅通、并在引力域的APP或小程序中打开`, position: `top`});
      return
    }
    setTimeout(() => {
      if (ev) {
        setENV(ev);
        return;
      }
      flag++;
      const resolve = checkENV();
      waitForAuth(resolve);
    }, 100);
  };

  const compHandler = {
    link: async (url) => {
      const env = await checkENV2();
      if (env === `mini`) {
        wx?.miniProgram.navigateTo({url: `/pages/subscribe/subscribe?id=17`})
      } else if (env === `app`) {
        const {type, value} = appTypeCheck(`https://head.uni.changan.com.cn/quanzi/#/zixunPreview?artId=2056`) || {};
        appNavigate(type, value);
      }
    },
    navigate: url => navigateTo(url),
    // 打开规则
    rule: () => {
      const m = callFeedback({
        bodyClassName: `rule-modal act-feedback-modal hidden-close`,
        title: <div>活动规则</div>,
        content: <div className="inner">  <RuleComp /></div>,
        actions: <>
          <AutoCenter><Button className="act-btn act-btn-bevel" onClick={() => m.close()}>确 定</Button></AutoCenter>
        </>,
        closeOnAction: true,
        hideClose:true,
        // showCloseButton: false,
        closeOnMaskClick: true,
      })
    },
    // 我的奖品
    prize: async () => {
      const resp = await requewt(API.lottery.remain);
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        return
      }
      const m = callFeedback({
        bodyClassName: `act-feedback-modal close-at-center-bottom`,
        content: <div className="inner"><PrizeComp /></div>,
        actions: <>
        <div style={{color:'#be9a45'}}>剩余抽奖次数{resp.data}次</div>
          <Grid columns={2} gap={10}>
        <Grid.Item style={{padding: '0 10px'}}>
        <Button shape={`rounded`}
                loading={loading}
                className="act-btn act-btn-bevel act-btn-green"
                onClick={e => m.close()}
        >
          返回首页
        </Button>
        </Grid.Item>
        <Grid.Item>
        <Button shape={`rounded`}
                loading={loading}
                className="act-btn act-btn-bevel"
                onClick={async e => navigateTo(`/wheel`)}
        >
          去抽奖
        </Button>
        </Grid.Item>
      </Grid>
        </>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    },
    // 点击分享
    pressShare:async () => {
      handleAppShareToH5()
    },
    close: () => {
      setVisible(undefined)
    },
    stuff: () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal close-at-center-bottom`,
        content: <div className="inner"><StuffComp /></div>,
        actions: <></>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    }
  }


  return (
    <div className={`cp-${klassName}`}>
      <div className="inner">
        {/*{*/}
        {/*  [`/rank`, `/tool`].includes(pathname) &&*/}
        {/*  <Button className="back-btn" onClick={e => Router.back()} fill="none">*/}
        {/*    <LeftOutline color="#333" />*/}
        {/*  </Button>*/}
        {/*}*/}

        <Space direction="vertical" size={[20, 20]} className="btn-group">
        <div key={1} className="side-btn" onClick={compHandler.rule}>
            活<br />
            动<br />
            规<br />
            则
          </div>
          <div key={3} className="side-btn" onClick={handleShowPrize}>
            我<br />
            的<br />
            奖<br />
            品
          </div>
          <div key={3} className="side-btn" onClick={e => compHandler.pressShare()}>
            分<br />
            享<br />
          </div>


        </Space>

      </div>

    </div>
  )
}